<!--  -->
<template>
  <div class="edit-img-wrap">
      <img :src="img" ref="img">
      <div class="bottom-box">
          <span class="cancel" @click="$emit('update-show')">取消</span>
          <span class="confirm" @click="onConfrim">完成</span>
      </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updatePhoto } from '@/api/editUserPhoto'
export default {
  name: 'EditImg',
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      aspectRatio: 16 / 9
    //   crop (event) {
    //     // console.log(event.detail.x)
    //     // console.log(event.detail.y)
    //     // console.log(event.detail.width)
    //     // console.log(event.detail.height)
    //     // console.log(event.detail.rotate)
    //     // console.log(event.detail.scaleX)
    //     // console.log(event.detail.scaleY)
    //   }
    })
  },
  methods: {
    onConfrim () {
      // 基于服务端的裁切，使用getData方法获取裁切参数
    //   console.log(this.cropper.getData())

      // 纯客户端的裁切使用getCroppedCanvas获取裁切对象
      this.$toast.loading('上传中')
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        // 注意看接口Content-Type为multipart/form-data要传递的是formData对象
        const formData = new FormData()
        formData.append('photo', blob)
        const res = await updatePhoto(formData)
        this.$emit('update-img', res.data.data.photo)
        this.$toast.success('上传成功')
        // 关闭弹出层
        this.$emit('update-show')
      })
    }
  }
}
</script>

<style  scoped lang = 'less'>
.edit-img-wrap {
  height: 100%;
  background-color: black;
  .bottom-box {
    position: fixed;
    bottom: 0;
    right: 0;
    left: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: white;
    font-size: 35px;
    margin: 0 20px 20px;
  }
  img {
    display: block;
    max-width: 100%;
  }
}
</style>
